package com.pinyoumei.app.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.WxBindBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.utils.event.WxLoginEvent;
import com.pinyoumei.app.view.LoadingDailog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2021-08-06.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-06        Administrator             新增Person类
 * 2021-08-06        Administrator             增加sex属性
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    protected AppManager appManager = AppManager.getInstance();
    private LoadingDailog loadingDailog;
    private Gson gson;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtils.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
        StatusBarUtils.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtils.setStatusBarDarkTheme(this, true)){
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtils.setStatusBarColor(this,0x55000000);
        }
        // 添加activity 到栈
        appManager.addActivity(this);

        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();

        setContentView(R.layout.activity_login);
        EventBusUtils.register(this);
        InitWidget();

    }


    private void InitWidget() {
        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        Button bt_register = findViewById(R.id.bt_register);
        bt_register.setOnClickListener(this);

        Button bt_login = findViewById(R.id.bt_login);
        bt_login.setOnClickListener(this);

        ImageView iv_wechat_login = findViewById(R.id.iv_wechat_login);
        iv_wechat_login.setOnClickListener(this);

        TextView tv_rule = findViewById(R.id.tv_rule);
        tv_rule.setOnClickListener(this);

        tv_rule.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEventMain(WxLoginEvent event) {
        if (!TextUtils.isEmpty(event.openid)) {

            WX_BING(event.openid,event.user_nick_name,event.user_head_img);
            EventBusUtils.removeStickyEvent(WxLoginEvent.class);
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.bt_register:
                startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
                break;

            case R.id.bt_login:
                startActivity(new Intent(LoginActivity.this,AccountLoginActivity.class));
                break;

            case R.id.iv_wechat_login:
                //微信登录
                loginWeixin(LoginActivity.this,"wxfcdbc78aac617cee");

                break;

            case R.id.tv_rule:
                 Intent intent = new Intent(LoginActivity.this, WebViewActivity.class);
                intent.putExtra("order_title", "");
                intent.putExtra("url",Constants.MAIN_URL + "h5/protocol");
                startActivity(intent);
                break;

            default:
                break;
        }
    }



    /**
     * 登录微信
     *
     * @param
     */
    public static void loginWeixin(Context context, String weixin_app_id) {

        if (TextUtils.isEmpty(weixin_app_id)) {
            Toast.makeText(context.getApplicationContext(), "app_id 不能为空", Toast.LENGTH_SHORT).show();
        }
        IWXAPI api = WXAPIFactory.createWXAPI(context, weixin_app_id, true);
        api.registerApp(weixin_app_id);

        // 判断是否安装了微信客户端
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context.getApplicationContext(), "您还未安装微信客户端！", Toast.LENGTH_SHORT).show();
            return;
        }
        // 发送授权登录信息，来获取code
        SendAuth.Req req = new SendAuth.Req();
        // 应用的作用域，获取个人信息
        req.scope = "snsapi_userinfo";
        /**
         * 用于保持请求和回调的状态，授权请求后原样带回给第三方
         * 为了防止csrf攻击（跨站请求伪造攻击），后期改为随机数加session来校验
         */
        req.state = "app_wechat";
        api.sendReq(req);
    }


    private void WX_BING(String open_id,String user_nick_name,String user_head_img) {
        Map<String, Object> map = new HashMap<>();
        map.put("open_id", open_id);

        OkGo.<String>post(Constants.IS_WX_BING)
                .params("open_id", open_id)
                .params("open_id", open_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        WxBindBean wxBindBean = gson.fromJson(response.body(), WxBindBean.class);

                        if (wxBindBean.getCode() >= 0) {
                            SPUtils.saveAppUserId(LoginActivity.this,wxBindBean.getResult().getUser_id());

                            SPUtils.saveUserPhone(LoginActivity.this,wxBindBean.getResult().getUser_phone());

                            SPUtils.saveUserPhone(LoginActivity.this,wxBindBean.getResult().getUser_phone());

                            startActivity(new Intent(LoginActivity.this,MainUIActivity.class));

                            finish();


                        } else {

                            Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                            intent.putExtra("open_id",open_id);
                            intent.putExtra("user_nick_name",user_nick_name);
                            intent.putExtra("user_head_img",user_head_img);
                            startActivity(intent);
                        }

                    }

                });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }
}
